using System;
using Microsoft.SPOT;
using NeonMika.Webserver.EventArgs;
using System.Collections;
using System.Threading;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using CodingSmackdown.Services;
using FastloadMedia.NETMF.Http;

namespace CodingSmackdown.TemperatureMonitor
{
    public class GetTemperatureMethod
    {
        public static bool GetTemperature(RequestReceivedEventArgs e, JsonArray h)
        {
            try
            {
                float totalReading = 0;

                for (int i = 0; i < 100; i++)
                {
                    totalReading += PinManagement.GetAnalogPinValue(0);
                    Thread.Sleep(10);
                }

                float averageReading = totalReading / 100;

                DateTime timeOfReading = DateTime.Now;
                float sensorMilliVolts = averageReading * 3300 / 1023;
                float temperatureCelsius = (sensorMilliVolts - 500) / 10;
                float temperatureFahrenheit = ((temperatureCelsius * 9) / 5) + 32;

                JsonObject reading = new JsonObject();
                reading.Add("timeOfReading", timeOfReading.ToString());
                reading.Add("sensorMilliVolts", sensorMilliVolts.ToString());
                reading.Add("temperatureCelsius", temperatureCelsius.ToString());
                reading.Add("temperatureFahrenheit", temperatureFahrenheit.ToString());

                h.Add(reading);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return true;
        }
    }
}
